package com.study.boot.activiti.controller;

import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.List;

/**
 * 流程控制器
 *
 * @author TangFD@HF 2018/5/2
 */
@Controller
public class IndexController {
    @Resource
    private RepositoryService repositoryService;

    @RequestMapping("/index")
    public String index() {
        return "index";
    }

    @GetMapping("process")
    public String process(Model model) {
        ProcessDefinitionQuery processDefinitionQuery = repositoryService.createProcessDefinitionQuery();
        List<ProcessDefinition> definitionList = processDefinitionQuery.list();
        model.addAttribute("definitionList", definitionList);
        return "process";
    }

    @GetMapping("/resource")
    @ResponseBody
    public void resource(@RequestParam String definitionId, @RequestParam String resource, HttpServletResponse response) throws Exception {
        ProcessDefinition def = repositoryService.createProcessDefinitionQuery().processDefinitionId(definitionId).singleResult();
        InputStream is = repositoryService.getResourceAsStream(def.getDeploymentId(), resource);
        ServletOutputStream output = response.getOutputStream();
        IOUtils.copy(is, output);
    }
}
